const app = getApp();

Page({
  data: {
    loading: true,
    orderState: [],
    orderList: [],
    previewVisiblePC: false,
    previewVisibleMobile: false,
    selectedImageIds: [],
    selectedOrderId: null,
    isMobile: false // 微信小程序不支持 window.innerWidth，需手动判断
  },

  onLoad() {
    this.setData({ isMobile: wx.getSystemInfoSync().windowWidth < 768 });
    this.fetchOrders();
  },

 // 获取记录列表
fetchOrders() {
  this.setData({ loading: true });
  app.request({
    url: '/user/order/getOrderList',
    method: 'GET',
    success: (res) => {
      if (res.code === 1) {
        this.setData({
          orderState: res.data.orderState,
        });
        const orderList = res.data.orderList.map(order => ({
          ...order,
          imageIdList: order.imageIdList || [],
          // 对每个记录的图片ID列表生成对应的 imageUrl 列表
          imagesWithUrl: (order.imageIdList || []).map(imageId => ({
            id: imageId,
            imageUrl: `${app.globalData.apiUrl}/user/minio/getImage/${imageId}`
          })),
          // 添加状态描述到记录对象中
          statusText: this.getOrderState(order.currentStatus)
        }));
        this.setData({
          orderState: res.data.orderState,
          orderList,
          loading: false
        });
      } else {
        wx.showToast({ title: res.msg, icon: 'none' });
        this.setData({ loading: false });
      }
    },
    fail: (err) => {
      wx.reLaunch({
        url: 'pages/user/UserHomeView/UserHomeView'
      });
      console.error(err);
      wx.showToast({ title: '获取记录失败', icon: 'none' });
      this.setData({ loading: false });
    }
  });
},

  // 获取状态文本
  getOrderState(index) {
    return this.data.orderState[index] || '未知状态';
  },

  // 获取图片地址
  getImageUrl(imageId) {
    return `${app.globalData.apiUrl}/user/minio/getImage/${imageId}`;
  },

  // 获取缩略图地址
  getThumbnailUrl(imageId) {
    return this.getImageUrl(imageId) + '?size=small';
  },

// 打开预览弹窗
openPreviewDialog(e) {
  const order = e.currentTarget.dataset.order;

  // 获取该记录下所有带 imageUrl 的图片 URL 列表
  const selectedImageUrls = (order.imagesWithUrl || []).map(img => img.imageUrl);

  this.setData({
    selectedImageIds: order.imageIdList,
    selectedImageUrls: selectedImageUrls, // 新增：保存图片 URL 列表
    selectedOrderId: order.id
  });

  if (this.data.isMobile) {
    this.setData({ previewVisibleMobile: true });
  } else {
    this.setData({ previewVisiblePC: true });
  }
},

  // 关闭预览弹窗
  closePreviewDialog() {
    this.setData({
      previewVisiblePC: false,
      previewVisibleMobile: false
    });
  },

  closePreviewDialog() {
    this.setData({
      previewVisiblePC: false,
      previewVisibleMobile: false
    });
  },
  // 下载当前记录的所有图片（压缩包）
  downloadImages() {
    const orderId = this.data.selectedOrderId;
    wx.showLoading({
      title: '获取链接中',
      mask: true
    });

    wx.setClipboardData({
      data: `${app.globalData.apiUrl}/user/minio/WXDownloadImage/${orderId}/${app.globalData.token}`,
      success: () => {
        wx.showToast({
          title: '已复制链接到剪贴板',
          icon: 'none',
          duration: 2500
        });
      },
      fail: () => {
        wx.showToast({
          title: '复制失败，请重试',
          icon: 'none'
        });
      }
    });
  },
  // 处理超级级别满意与否
  handleSuperOrder(e) {
    const { orderId, state } = e.currentTarget.dataset;

    app.request({
      url: `/user/order/updateSuperOrder/${orderId}/${state}`,
      method: 'PUT',
      success: (res) => {
        if (res.code === 1) {
          wx.showToast({ title: '操作成功' });
          this.fetchOrders(); // 刷新列表
        } else {
          wx.showToast({ title: res.msg, icon: 'none' });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '请求失败', icon: 'none' });
        console.error(err);
      }
    });
  },

  // 返回主页
  goHome() {
    wx.redirectTo({
      url: '/pages/user/UserHomeView/UserHomeView'
    });
  },
   // 跳转到上传页面
   goToUpload() {
    wx.navigateTo({
      url: '/pages/user/UploadImageView/UploadImageView'
    });
  },
  void(){}
});